package dk.itu.pervasive.jcaf;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Observable;
import java.util.Observer;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class AsyncConnection extends Observable implements Runnable {

	private String bluetoothID;
	
	public AsyncConnection(Observer obs, String bt_id) {
		this.addObserver(obs);
		this.bluetoothID = bt_id;
	}

	@Override
	public void run() {

		// while (true) {

		Log.i("mapou", "run() method reached ");

		WifiManager wifi = (WifiManager) Visitor_At_ITU_Activity.getAppContext().getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		
		boolean notificationPending = true;
		while (notificationPending) {

			String ssid = info.getSSID();
			Log.i("mapou", "SSID: " + ssid);
			
			if (ssid != null && (ssid.equals("ITU") || ssid.equals("eduroam") || ssid.equals("WEB-AUTH") )) {
				try {
					Log.i("mapou", "Trying to connect ...");
					Socket con =  new Socket("10.25.240.153", 12345); // Martin: 10.27.244.238 - Anne: 10.27.216.254 - Jesper: 10.25.240.153
					PrintStream out = new PrintStream(con.getOutputStream());
					if (bluetoothID != null) {
						out.write(bluetoothID.getBytes()); // out.write("1846178d12b3".getBytes());
					} else {
						out.write("NO BLUETOOTH ID WAS GIVEN TO AsyncConnection".getBytes());
					}
					out.write(0); // '0' marks the end of a message // but bluetooth id could contain zero ??
					out.flush();
					con.close();
					notificationPending = false;
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		setChanged();
		notifyObservers("\nLOCATED AT ITU, JCAF NOTIFIED");
	}

}
